package com.easyban.config;

import com.easyban.Dto.SysSettingsDto;
import com.easyban.constants.Constants;
import com.easyban.exception.BusinessException;

import com.easyban.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Date;


@Component
public class EmaileCode {
    private static final Logger logger= LoggerFactory.getLogger(EmaileCode.class);
    @Resource
    private WebConfig webConfig;
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private RedisUtils redisUtils;
    public void sendEmailCode(String toEmail, String code) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();

            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //邮件发件人
            helper.setFrom(webConfig.getSendUserName());
            //邮件收件人 1或多个
            helper.setTo(toEmail);

        //    SysSetting4EmailDto emailDto = SysCacheUtils.getSysSetting().getEmailSetting();
            //邮件主题
            SysSettingsDto value = (SysSettingsDto) redisUtils.getValue(Constants.REDIS_KEY_SYS_SETTING);
            //邮件主题
            helper.setSubject(value.getRegisterEmailTitle());
            String emailContent = value.getRegisterEmailContent();
            //邮件内容
            helper.setText(String.format(emailContent, code));
            //邮件发送时
            helper.setSentDate(new Date());
            javaMailSender.send(message);
        } catch (Exception e) {
            logger.error("邮件发送失败", e);
            throw new BusinessException("邮件发送失败");
        }
    }
}
